package sf.core.event;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import com.google.gson.Gson;

import sf.core.common.ReceiptStatus;
import sf.core.common.RedisMessageEntity;
import sf.core.entity.TfReceipt;

/**
 * Created by ligen on 15-10-30.
 */
public abstract class RedisSubscriber implements MessageListener {

	Gson gson = new Gson();

	Logger logger = LoggerFactory.getLogger(this.getClass());

	protected HashMap<Integer, String> receiptStatusMap = new HashMap<Integer, String>();

	public RedisSubscriber() {
		receiptStatusMap.put(ReceiptStatus.STATUS_BOOKED, "预约");
		receiptStatusMap.put(ReceiptStatus.STATUS_CANCELD, "取消");
		receiptStatusMap.put(ReceiptStatus.STATUS_VERIFIED, "核销");
	}

	@Override
	public void onMessage(Message message, byte[] pattern) {

		String channel = new String(pattern);
		logger.error(String.join(":", channel, message.toString()));
		if (channel.equals(SugarEvent.RECEIPT_STATUS_CHANGED)) {
			logger.debug("from channel " + SugarEvent.RECEIPT_STATUS_CHANGED);
			onReceiptStatusChanged(retrieveReceipt(message));
		}
		if (channel.equals(XTRedisPublisher.CHANNEL)) {
			logger.debug("from channel " + XTRedisPublisher.CHANNEL);
			onMessaga(retrieveRedisMessage(message));
		}
	}

	private TfReceipt retrieveReceipt(Message message) {
		return gson.fromJson(message.toString(), TfReceipt.class);
	}

	private RedisMessageEntity retrieveRedisMessage(Message message) {
		logger.debug("redisMessags : " + gson.toJson(message));
		return gson.fromJson(message.toString(), RedisMessageEntity.class);
	}

	public abstract void onReceiptStatusChanged(TfReceipt receipt);

	public abstract void onMessaga(RedisMessageEntity message);
}
